<template>
  <div class="group-management-container">
    <n-layout>
      <n-layout-header bordered>
        <div class="header-content">
          <h1>分组管理</h1>
          <div class="header-actions">
            <n-button type="primary" @click="showCreateModal">
              <template #icon>
                <n-icon><Add /></n-icon>
              </template>
              新建分组
            </n-button>
            <n-button @click="handleLogout">
              退出
            </n-button>
          </div>
        </div>
      </n-layout-header>
      
      <n-layout-content class="content">
        <n-list>
          <n-list-item v-for="group in groups" :key="group.group_id">
            <n-thing>
              <template #header>
                <div class="group-header">
                  <span>{{ group.name }}</span>
                  <n-tag v-if="group.is_default" type="info" size="small">默认</n-tag>
                </div>
              </template>
              <template #description>
                <div class="group-meta">
                  <span>任务数: {{ group.task_count || 0 }}</span>
                  <span>创建时间: {{ formatDate(group.created_at) }}</span>
                </div>
              </template>
              <template #header-extra v-if="!group.is_default">
                <n-button-group>
                  <n-button text @click="() => editGroup(group)">
                    <n-icon><Create /></n-icon>
                  </n-button>
                  <n-button text @click="() => deleteGroup(group.group_id)">
                    <n-icon><Trash /></n-icon>
                  </n-button>
                </n-button-group>
              </template>
            </n-thing>
          </n-list-item>
        </n-list>
      </n-layout-content>
    </n-layout>
    
    <!-- 创建/编辑分组模态框 -->
    <n-modal v-model:show="showModal" preset="dialog" :title="modalTitle">
      <n-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
      >
        <n-form-item label="分组名称" path="name">
          <n-input v-model:value="formValue.name" placeholder="请输入分组名称" />
        </n-form-item>
      </n-form>
      <template #action>
        <n-button @click="showModal = false">取消</n-button>
        <n-button type="primary" @click="handleSave" :loading="loading">{{ modalConfirmText }}</n-button>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import type { FormInst, FormRules } from 'naive-ui'
import { Add, Create, Trash } from '@vicons/ionicons5'

// 导入所有使用的Naive UI组件
import {
  NLayout,
  NLayoutHeader,
  NLayoutContent,
  NButton,
  NButtonGroup,
  NForm,
  NFormItem,
  NInput,
  NList,
  NListItem,
  NThing,
  NModal,
  NTag,
  NIcon
} from 'naive-ui'

import { useGroupStore } from '../../stores/groupStore'
import { useUserStore } from '../../stores/userStore'
import type { TaskGroup } from '../../types/group'

const router = useRouter()
const message = useMessage()
const groupStore = useGroupStore()
const userStore = useUserStore()

// 状态
const showModal = ref(false)
const isEditing = ref(false)
const currentGroupId = ref<number | null>(null)
const loading = ref(false)

// 表单引用
const formRef = ref<FormInst | null>(null)

// 表单数据
const formValue = ref({
  name: ''
})

// 表单规则
const rules: FormRules = {
  name: {
    required: true,
    message: '请输入分组名称',
    trigger: 'blur'
  }
}

// 计算属性
const groups = computed(() => groupStore.getAllGroups)

const modalTitle = computed(() => isEditing.value ? '编辑分组' : '新建分组')
const modalConfirmText = computed(() => isEditing.value ? '更新' : '创建')

// 方法
const showCreateModal = () => {
  isEditing.value = false
  currentGroupId.value = null
  formValue.value.name = ''
  showModal.value = true
}

const editGroup = (group: TaskGroup) => {
  isEditing.value = true
  currentGroupId.value = group.group_id
  formValue.value.name = group.name
  showModal.value = true
}

const deleteGroup = async (groupId: number) => {
  const result = await groupStore.deleteGroup(groupId)
  if (result.success) {
    message.success('分组删除成功')
    
    // 重新获取分组列表以确保数据一致性
    await groupStore.fetchGroups()
  } else {
    message.error(result.message || '分组删除失败')
  }
}

const handleSave = () => {
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        loading.value = true
        let result
        if (isEditing.value && currentGroupId.value) {
          result = await groupStore.updateGroup(currentGroupId.value, formValue.value.name)
        } else {
          result = await groupStore.createGroup(formValue.value.name)
        }
        
        if (result.success) {
          message.success(isEditing.value ? '分组更新成功' : '分组创建成功')
          showModal.value = false
          formValue.value.name = ''
          
          // 重新获取分组列表以确保数据一致性
          await groupStore.fetchGroups()
        } else {
          message.error(result.message || (isEditing.value ? '分组更新失败' : '分组创建失败'))
        }
      } catch (error) {
        message.error(isEditing.value ? '分组更新过程中发生错误' : '分组创建过程中发生错误')
      } finally {
        loading.value = false
      }
    }
  })
}

const handleLogout = () => {
  userStore.logout()
  router.push('/login')
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 生命周期
onMounted(async () => {
  await groupStore.fetchGroups()
})
</script>

<style scoped>
.group-management-container {
  height: 100vh;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
}

.content {
  padding: 16px;
}

.group-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.group-meta {
  display: flex;
  gap: 16px;
  margin-top: 4px;
  font-size: 12px;
  color: #999;
}
</style>